<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class HandanController extends Controller{
//    public $tel = '';
//    
//    public function __construct(Request $request) {
//        $this->tel = $request->session()->get('eai')['tel'];
//    }
    public function hd(Request $request){   //我的策略
        $session_data = $request->session()->get('eai');
        
        //交易动态
         $jiaoyiWhere = array('ispersonal'=>0,'isstop'=>0,'trade_status'=>'1');   
         $jiaoyiData = DB::table('waihui_order')
            ->join('waihui_member', 'waihui_order.tel', '=', 'waihui_member.tel')
            ->select('waihui_member.username','waihui_member.photo','waihui_order.final_point as yingkui','waihui_order.begin_point','waihui_order.trade_status','waihui_order.end_point','waihui_order.buy_status','waihui_order.typename')
            ->where($jiaoyiWhere)
            ->where('waihui_order.final_point','>',10)
            ->limit(6)
            ->orderBy('waihui_order.end_time','desc')
            ->get()
            ->toArray();
        $return['jiaoyi']=$jiaoyiData;
         
        if($session_data){  // 获取用户当前持仓单
            $where=array('tel'=>$session_data['tel'],'isstop'=>1);   
            $data = DB::table('waihui_order as o')->join('waihui_type as t','o.typename','t.name')->select('t.chinaname','o.tradeid','o.typename','o.buy_status','o.begin_time','o.begin_point','o.profit_point','o.loss_point','o.target_profit_point','o.target_loss_point','o.other_begin_point')->where($where)->get()->toArray();  
            //dd($data);
            $alltype = array();
            if($data){
                foreach($data as $key=>$val){
                    $alltype[] = 'FX'.$val->typename;
                    $data[$key]->buy_status = ( $val->buy_status == 0 ? '买入' : '卖出') ;
                    $data[$key]->begin_time = date('Y-m-d H:i:s',$data[$key]->begin_time);
                }
                $alltype = implode(',',$alltype);
               
                $count = count($data);
                if($count>0){ 
                    $return['count']=$count;
                    $return['data']=$data;
                }else{ 
                    $return['count']=0;
                }
                $return['status']=1;
            }else{
                $return['status']=0;
                $return['count']=0;
                $alltype = '';
            }
 
        }else{
            $return['status']=0;
            $return['count']=0;
            $return['data']='';
            $alltype = '';
        }
        $starttime  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上5:00:00
        $endtime    = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
        if(isMobile()){
           $typename = trim($request->get('typename'));
            if($session_data){
                $sumfinal = DB::table('waihui_order')->where(array('tel'=>$session_data['tel']))->select(DB::raw("SUM(final_point) AS final_point"))->get()->toArray();
                $sumfinal = $sumfinal[0]->final_point;
            }else{
                $sumfinal = 0;
            }
            return view('mobile.hangqing', compact('return','starttime','endtime','alltype','sumfinal','typename'));
        }else{
            //交易动态
            $jiaoyiWhere = array('ispersonal'=>0,'isstop'=>0,'trade_status'=>'1');
            $jiaoyiData = DB::table('waihui_order')
                            ->join('waihui_member', 'waihui_order.tel', '=', 'waihui_member.tel')
                            ->select('waihui_member.username','waihui_member.photo','waihui_order.final_point as yingkui','waihui_order.begin_point','waihui_order.trade_status','waihui_order.end_point','waihui_order.buy_status','waihui_order.typename')
                            ->where($jiaoyiWhere)
                            ->where('waihui_order.final_point','>',0)
                            ->limit(6)
                            ->orderBy('waihui_order.end_time','desc')
                            ->get()
                            ->toArray();
            $return['jiaoyi']=$jiaoyiData;
            return view('handan', compact('return','starttime','endtime'));
        }
    }
    
    public function testSocket(){
        return view('socket');
    }

    //获取交易订单ID
    public function  GetTradeId(){
        //年（2017年：A;2018年：B）
        $year_code = array('A','B','C','D','E','F','G','H','I','J');
        $order_sn  = $year_code[intval(date('Y'))-2017];
        //月日（4月11号：411；10月3号：A03;11月11号：B11）
        $date      = strtoupper(dechex(date('m'))).date('d');
        //年月日 + 微妙时间戳后四位+二位的整数
        $ID = $order_sn.$date.substr(microtime(),2,4).sprintf('%02d',rand(0,99));
        return $ID;
    }

    //socket传输操作
    public static function socketHandle($content){
        header("Content-Type: text/html; charset=GB2312");
        set_time_limit(0);
        $host="101.37.76.105";
        $port=8099;
        //创建一次 实现多次通信
        $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
        $conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");
        socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 10);

        socket_write($socket,$content) or die("cannot write data\n");

        $buffer=socket_read($socket,1024,PHP_BINARY_READ);
        usleep(1000);
        socket_close($socket);
        if($buffer)
        {
            return $buffer;
        }

    }
    
    

    //获取分析师持仓数量信息：1、一个品种下持仓状态只能有一单; 2、所有品种下的持仓数不能超过3单
    public function  getOrderStatus(Request $request){
        $session_data = $request->session()->get('eai');
        if($session_data){
            $userinfo = DB::table('waihui_member')
                    ->select('username','hasapply','applytime','sex','email','birthday','server_name')
                    ->where('id','=',$session_data['id'])
                    ->first();
            if(!$userinfo){
                $return['status'] = 5; //没有该用户
            }else{
                $moreinfo = DB::table('waihui_member_info')->select('province','city','country')->where('userid','=',$session_data['id'])->first();
                if(!$moreinfo){
                    $return['status'] = 4;  //资料未全部完善
                }else if($userinfo->username == '' || $userinfo->sex == '' || $userinfo->email == ''|| $userinfo->birthday == '' || $moreinfo->province == '' || $moreinfo->city == '' || $moreinfo->country == '' || $userinfo->server_name == ''){
                    $return['status'] = 4;  //资料未全部完善
                }else{
                    $num = DB::table('waihui_order')->where([['isstop', '=', '1'], ['tel', '=', $session_data['tel']]])->count();
                    if($num < 3){
                        $typename = trim($request->typename);
                        $cur_point = floatval(trim($request->point));
                        $fangxiang = trim($request->fangxiang);
                        $checkorder = DB::table('waihui_order')->select('buy_status','begin_point')->where([['typename','=',$typename],['isstop', '=', '1'], ['tel', '=', $session_data['tel']]])->orderBy('id','desc')->get()->toArray();
                        if($checkorder){ // 判读当前品种的盈亏情况
                            if($checkorder[0]->buy_status != $fangxiang){
                                //盈利加仓方向不一致
                                $return['status'] = 0;
                                $return['msg']    = '方向不一致，不能加仓';
                            }else{
                                //盈利加仓方向一致
                                $profitpoint = HandanController::profitPoint($fangxiang,$typename,$cur_point,$checkorder[0]->begin_point);
                                if($profitpoint < 0){ //当前盈利是否>0
                                    $return['status'] = 0;
                                    $return['msg']    = '前一单盈利为负，不能加仓！';
                                }else{
                                    $return['status'] = 1;
                                    $return['msg']    = '所有品种下的持仓状态数未达上限';
                                }
                            }
                        }else{
                            $return['status'] = 1;
                            $return['msg']    = '所有品种下的持仓状态数未达上限';
                        }
                    }else{//所有品种下的持仓数不能超过3单
                        $return['status'] = 3;
                        $return['msg']    = '持仓状态不能超过3单';
                    }

                }
            }             
        }else{
             $return['status'] = 2;
        }
        
        return json_encode($return);
    }
    //计算盈利点位
    public function profitPoint($buy_status,$typename,$cur_point,$begin_point){
        if($buy_status == 1){   //即卖出
            if($typename == 'XAUUSD'){   //黄金数据类型点位计算
                $point  = round((($begin_point -$cur_point-1)*10),2); //盈利点位
            }else if($typename == 'NYOL20'){
                $point  = round((($begin_point -$cur_point-0.1)*100),2); //盈利点位
            }else if(stripos($typename,'JPY')){
                $point  = round((($begin_point -$cur_point-0.1)*100),3); //盈利点位
            }else{
                $point  = round((($begin_point -$cur_point-0.001)*10000),5); //盈利点位
            }
        }else if($buy_status == 0){  //即买入    }else{  //货币兑数据类型点位计算
            if($typename == 'XAUUSD'){   //黄金数据类型点位计算
                $point = round((($cur_point -$begin_point-1)*10),2); //盈利点位
            }else if($typename == 'NYOL20'){
                $point = round((($cur_point -$begin_point-0.1)*100),2); //盈利点位
            }else if(stripos($typename,'JPY')){
                $point = round((($cur_point -$begin_point-0.1)*100),3); //盈利点位
            }else{
                $point = round((($cur_point -$begin_point-0.001)*10000),5); //盈利点位
            }
        }
        return $point;
    }
    
    //计算止盈止损点位,方向，品种，当前点位，止损点数,止盈点数
    public function calculatePoint($buy_status,$typename,$cur_point,$target_loss_point,$target_profit_point,$other_point){ 
        $target_sell_point = 0;
        $target_buy_point  = 0;
        if($buy_status == 1){   //即卖出
            if($typename == 'XAUUSD'){   //黄金数据类型点位计算
                $target_sell_point = round(($cur_point +$target_loss_point/10),2); //止损点位
                $target_buy_point  = round(($cur_point -$target_profit_point/10),2); //止盈点位
            }else if($typename == 'NYOL20'){
                $target_sell_point = round(($cur_point +$target_loss_point/100),2); //止损点位
                $target_buy_point  = round(($cur_point -$target_profit_point/100),2); //止盈点位
            }else if(stripos($typename,'JPY')){
                if(stripos($typename,'USD')){ //如果不是交叉盘
                    $target_sell_point = round(($cur_point +$target_loss_point/100),3); //止损点位
                    $target_buy_point  = round(($cur_point -$target_profit_point/100),3); //止盈点位
                }else{
                    $target_sell_point = round(($other_point +$target_loss_point/100),3); //止损点位
                    $target_buy_point  = round(($other_point -$target_profit_point/100),3); //止盈点位
                }
                
            }else{
                if(stripos($typename,'USD')){ //如果不是交叉盘
                    $target_sell_point = round(($cur_point +$target_loss_point/10000),5); //止损点位
                    $target_buy_point  = round(($cur_point -$target_profit_point/10000),5); //止盈点位
                }else{
                    $target_sell_point = round(($other_point +$target_loss_point/10000),5); //止损点位
                    $target_buy_point  = round(($other_point -$target_profit_point/10000),5); //止盈点位
                }
                
            }
        }else if($buy_status == 0){  //即买入    }else{  //货币兑数据类型点位计算
            if($typename == 'XAUUSD'){   //黄金数据类型点位计算
                $target_sell_point = round(($cur_point -$target_loss_point/10),2); //止损点位
                $target_buy_point  = round(($cur_point +$target_profit_point/10),2); //止盈点位
            }else if($typename == 'NYOL20'){
                $target_sell_point = round(($cur_point -$target_loss_point/100),2); //止损点位
                $target_buy_point  = round(($cur_point +$target_profit_point/100),2); //止盈点位
            }else if(stripos($typename,'JPY')){
                if(stripos($typename,'USD')){ //如果不是交叉盘
                    $target_sell_point = round(($cur_point -$target_loss_point/100),3); //止损点位
                    $target_buy_point  = round(($cur_point +$target_profit_point/100),3); //止盈点位
                }else{
                    $target_sell_point = round(($other_point -$target_loss_point/100),3); //止损点位
                    $target_buy_point  = round(($other_point +$target_profit_point/100),3); //止盈点位
                }
                
            }else{
                if(stripos($typename,'USD')){ //如果不是交叉盘
                    $target_sell_point = round(($cur_point -$target_loss_point/10000),5); //止损点位
                    $target_buy_point  = round(($cur_point +$target_profit_point/10000),5); //止盈点位
                }else{
                    $target_sell_point = round(($other_point -$target_loss_point/10000),5); //止损点位
                    $target_buy_point  = round(($other_point +$target_profit_point/10000),5); //止盈点位
                }
                
            }
        }
        $arr[0] = $target_sell_point;
        $arr[1] = $target_buy_point;
        return $arr;
        
    }
    
    
    public function sendBaoWen($baoweninfo,$type){  //发送报文,参数为报文的内容
        $infoResult   = HandanController::socketHandle($baoweninfo);  //反向
        $infoSubstr   = substr($infoResult, 0 ,  (strlen($infoResult)-1));
        $info   = json_decode($infoSubstr,true);
        Storage::append($type.'.txt', date('Y-m-d H:i:s').$baoweninfo.'返回报文状态值：'.$info['ret_code']);//缓存数据
        return $info;
    }
    

    //分析师策略
    public  function  gotoHandan(Request $request){
        $session_data = $request->session()->get('eai');
        $return=array();
        if($session_data){  //如果用户已登录
            $tradeid=HandanController::GetTradeId();
            $typename = htmlspecialchars(trim($request->typename));
            $buy_status = htmlspecialchars(trim($request->status));
            
            if($buy_status !=0 && $buy_status !=1) {
                $return['status']=0;  //策略失败
                return json_encode($return);
            }
//            else{
//                $buy_status = intval($buy_status);
//            }
            $cur_point = trim($request->cur_point); //卖出
            if($cur_point == 0){
                $return['status']=0;  //策略失败
                return json_encode($return);
            }
            $loss_point = $target_loss_point = intval(trim($request->target_loss_point));  // 用户设置的止损点 
            if($loss_point<=10 || $loss_point >=100){
                $return['status']=0;  //策略失败
                return json_encode($return);
                
            }
            $other_point = trim($request->other_point);  //买入
            $profit_point =  $target_profit_point = intval(trim($request->target_profit_point));  // 用户设置的止赢点
            
            if($profit_point<=10 || $profit_point >=500){
                $return['status']=0;  //策略失败
                return json_encode($return);
                
            }
            $time=strtotime('now');
            
            //正向订单止盈止损点计算
            $zhengarr   = HandanController::calculatePoint($buy_status,$typename,$cur_point,$target_loss_point,$target_profit_point,$other_point);
            $target_sell_point = $zhengarr[0];
            $target_buy_point =  $zhengarr[1];
            
            //正向订阅
            $infodata="{   
              head: {
                account: '$session_data[tel]',
                tradecode: 8801
              },
              body: {
                fromsource: 'netpage',
                mt4_login: '',
                company: '',
                mt4_orderid :'',
                trader_orderid : '$tradeid',
                symbol: '$typename',
                ordertype: $buy_status,
                lots: '',
                openprice:$cur_point,
                stoploss: $target_sell_point,
                takeprofit: $target_buy_point,
                comment:'',
                magic:0,
                account_balance:'',
                opentime:$time,
                closetime:'0',
                profit:0,
                direct:0
              }
           }&
           ";

            
            //反向订单止盈止损点计算
            $fbuy_status = $buy_status == 0 ? 1 :0;   //反向状态
            $fanarr   = HandanController::calculatePoint($fbuy_status,$typename,$other_point,$target_loss_point,$target_profit_point,$cur_point);
            $fanxiang_target_sell_point = $fanarr[0];
            $fanxiang_target_buy_point =  $fanarr[1];
            
            $fanxianginfodata="{
              head: {
                account: '$session_data[tel]',
                tradecode: 8801
              },
              body: {
                fromsource: 'netpage',
                mt4_login: '',
                company: '',
                mt4_orderid :'',
                trader_orderid : '$tradeid',
                symbol: '$typename',
                ordertype: $fbuy_status,
                lots: '',
                openprice:$other_point,
                stoploss: $fanxiang_target_sell_point,
                takeprofit: $fanxiang_target_buy_point,
                comment:'',
                magic:0,
                account_balance:'',
                opentime:$time,
                closetime:'0',
                profit:0,
                direct:1   
              }
           }&
           ";

            $data=[
                'tradeid' => $tradeid,
                'tel' => $session_data['tel'],
                'begin_time' =>  $time,
                'buy_status' => $buy_status,
                'begin_point' => $cur_point, //进厂点位
                'typename' => $typename,
                'target_profit_point' => $target_buy_point,   //止盈点位
                'target_loss_point' => $target_sell_point,    //止损点位
                'other_begin_point' => $other_point, //反向进厂点位
                'other_target_profit_point' => $fanxiang_target_buy_point,   //反向止盈点位
                'other_target_loss_point' => $fanxiang_target_sell_point,    //反向止损点位
                'isstop' => 1,
                'ispersonal' => 0,
                'profit_point'=>$profit_point,
                'loss_point'=>$loss_point
            ];
            //dd($data);
           // 判断订阅该分析师的客户，是否正向，反向都有 
           $direction= DB::table('waihui_follow')->where([['analyst_id','=',$session_data['id']],['status','=','1']])->pluck('direction');
           $direc=array();
           foreach ($direction as $d) {
               $direc[]=$d;
           }
           $direc=array_unique($direc);
           
            $info_zheng='';
            $info_fan='';
            if($direc){    //如果有人订阅该分析师
                if(count($direc) == 2){
                    $info_zheng = HandanController::sendBaoWen($infodata,'handan'); //正向
                    $info_fan = HandanController::sendBaoWen($fanxianginfodata,'handan'); //反向
//                    Storage::append('handan.txt', date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info_zheng['ret_code']);//缓存数据
//                    Storage::append('handan.txt', date('Y-m-d H:i:s').$fanxianginfodata.'返回报文状态值：'.$info_fan['ret_code']);//缓存数据
                    if($info_zheng['ret_code'] == '0000' && $info_fan['ret_code'] == '0000'){
                        $id = DB::table('waihui_order')->insertGetId($data);
                        if($id){
                            $return['status']=1;  //策略成功
                        }else{
                            $return['status']=0;  //策略失败
                        }
                    }else{
                        $return['status']=0;  //策略失败
                    }
                }else if(count($direc) == 1){
                    if(in_array('1', $direc)){
                        $info_fan = HandanController::sendBaoWen($fanxianginfodata,'handan'); //反向
//                        Storage::append('handan.txt', date('Y-m-d H:i:s').$fanxianginfodata.'返回报文状态值：'.$info_fan['ret_code']);
                        if($info_fan['ret_code'] == '0000'){
                            $id = DB::table('waihui_order')->insertGetId($data);
                            if($id){
                                $return['status']=1;  //策略成功
                            }else{
                                $return['status']=0;  //策略失败
                            }
                        }else{

                            $return['status']=0;  //策略失败
                        }
                    }else{
                        $info_zheng = HandanController::sendBaoWen($infodata,'handan'); //正向
//                        Storage::append('handan.txt', date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info_zheng['ret_code']);
                        if($info_zheng['ret_code'] == '0000'){
                            $id = DB::table('waihui_order')->insertGetId($data);
                            if($id){
                                $return['status']=1;  //策略成功
                            }else{
                                $return['status']=0;  //策略失败
                            }
                        }else{

                            $return['status']=0;  //策略失败
                        }
                    }
                }
               
                
            }else{   //如果没有人订阅该分析师
                    $id = DB::table('waihui_order')->insertGetId($data);
                    if($id){
                        $return['status']=1;  //策略成功
                    }else{
                        $return['status']=0;  //策略失败
                    }
            }
        }else{
            $return['status']=2;
        }
        return json_encode($return);
    }
    
    
    public function closeOut(Request $request){   //平仓
        $session_data = $request->session()->get('eai');
        if($session_data){
            $pingcangType = trim($request->pingcangType);  //平仓类型，单独平仓0 还是批量平仓1
            //安全验证
            if(!is_numeric($pingcangType)){  
                return json_encode(array('status'=>0)); 
                
            }else if($pingcangType !=0 && $pingcangType != 1){
                return json_encode(array('status'=>0)); 
                
            }
            
            $data['tradeid'] = $tradeid  = htmlspecialchars(trim($request->tradeid));
            $data['end_point'] = htmlspecialchars(trim($request->end_point));
            $data['typename']  = htmlspecialchars(trim($request->name));
            $data['final_point']  = htmlspecialchars(trim($request->final_point));
            $buy_status        = (trim($request->buy_status) == '买入' ? 0:1);
            $data['end_time']  = strtotime('now');
            $data['isstop']    = 0;
            $data['stop_status'] = '0';   //手动平仓
            
            
            //查询数据库有没有这条订单
            $where=array('tradeid'=>$data['tradeid'],'typename'=>$data['typename'],'buy_status'=>"$buy_status",'tel'=>$session_data['tel'],'isstop'=>1,'ispersonal'=>0);  
            $list = DB::table('waihui_order')->select('id','begin_point')->where($where)->first();
           
            if($list){
                //echo 'ddd';
                // 判断订阅该分析师的客户 
                $direction= DB::table('waihui_follow')->where([['analyst_id','=',$session_data['id']],['status','=','1']])->first();
                if($direction && $pingcangType == 0){    //如果有人订阅该分析师 并且是单独平仓
                    //echo 'gggggggggg';
                    //正向订阅
                    $infodata="{   
                        head: {
                          account: '$session_data[tel]',
                          tradecode: 8803,
                          allsend:0
                        },
                        body: {
                            fromsource: 'netpage',
                            trader_orderid : '$tradeid',
                        }
                    }&
                    ";
                    
                    $info_zheng = HandanController::sendBaoWen($infodata,'close'); //正向
//                    Storage::append('close.txt', date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info_zheng['ret_code']);
                    if($info_zheng['ret_code'] != '0000'){
                       // echo 'jjjjjjjjjjjjjjj';
                        return json_encode(array('status'=>0));   //平仓失败
                    }
                }
                
                if($data['final_point'] > 0){   //盈利
                    $data['trade_status'] = '1'; 
                }else if($data['final_point'] == 0){  //不亏不损
                    $data['trade_status'] = '2';
                    $data['money'] = 0;
                }else{  //亏损
                    $data['trade_status'] = '0';
                    $data['money'] = 0;
                }  
                
                $where = array('id'=>$session_data['id']);
                $memberInfo = DB::table('waihui_member')
                            ->select('grade','alltraid','liansheng','lianbai','star','authstatus','isanalyst')
                            ->where($where)
                            ->first();
               
                if($memberInfo){
                    if($memberInfo->grade != '-1'){  //如果用户已定级
                        if($data['final_point'] > 0){  //如果当前订单是盈利的，那么连胜字段+1，连败字段=0
                            $memberUpdateData = array('alltraid'=>$memberInfo->alltraid+1,'liansheng'=>$memberInfo->liansheng+1,'lianbai'=>0);
                        }else{  //如果当前订单是亏损的，那么连败字段+1，连剩字段=0
                            $memberUpdateData = array('alltraid'=>$memberInfo->alltraid+1,'lianbai'=>$memberInfo->lianbai+1,'liansheng'=>0);
                        }
                        
                        $todayBeginTime=mktime(0,0,0,date('m'),date('d'),date('Y'));
                        if($data['final_point'] > 10 && $memberInfo->authstatus == 2 && $memberInfo->isanalyst == 1){
                            $sum = DB::table('waihui_order')  //用户今天已平仓的单数,如果小于3单，那么有奖励，否则没有
                                    ->select(DB::raw('count(id) as sum'))
                                    ->where([['tel','=',$session_data['tel']],['ispersonal','=',"0"],['isstop','=','0'],['end_time','>',$todayBeginTime]])
                                    ->pluck('sum');
                           
                            $qianjidan = getenv('qianjidan');  //暂时是3单
                            if($sum && $sum[0] < $qianjidan){  
                                if($memberInfo->grade == 0){   //根据用户的等级定奖金
                                    $data['money'] = 0;
                                }else if($memberInfo->grade == 1){
                                    $data['money']=  getenv('gaoshou');
                                }else if($memberInfo->grade == 2){
                                    $data['money']=  getenv('zhuanjia');
                                }else if($memberInfo->grade == 3){
                                    $data['money']=  getenv('dashi');
                                }else if($memberInfo->grade == 4){
                                    $data['money']=  getenv('zongshi');
                                }
                            }else{
                                $data['money'] = 0;
                            }
                          
                        }else{
                            $data['money'] = 0;
                        }


                    }else{  //如果用户没有定级
                        //echo $memberInfo->alltraid;
                        $memberUpdateData = array('alltraid'=>$memberInfo->alltraid+1);
                        $data['money']= 0;
                    }
                    //print_r($memberUpdateData);  
                    $updateAlltrade = DB::table('waihui_member')->where('id',$session_data['id'])->update($memberUpdateData);
                    if(!$updateAlltrade){
                       // echo 'ttttttttttttttttt';
                        return json_encode(array('status'=>0));   //数据有错
                        
                    }
                }else{
                   // echo 'qqqqqqqqqqqqqqqqqq';
                    return json_encode(array('status'=>0));   //数据有错，数据库没有此人
                    
                }
               
                $userInfo = DB::table('waihui_member')  //更新完数据后，重新查询新数据
                            ->select('alltraid','grade','liansheng','star','lianbai')
                            ->where($where)
                            ->first();
                $dingjinum = getenv('dingjinum');
                $liansheng = getenv('liansheng');
                $lianbai = getenv('lianbai');
                $user = '';
                if($userInfo && $userInfo->alltraid == $dingjinum){  //当用户策略量=30单，给用户定级
                    $prifitSum = DB::table('waihui_order')   //策略盈利单数
                                ->select(DB::raw('count(id) as num'))
                                 ->where([['tel','=',$session_data['tel']],['trade_status','=',"1"],['ispersonal','=','0'],['isstop','=','0']])
                                 ->first();
                    
                    if($prifitSum->num <= 14){  //0-14单
                        $user['grade'] = '0';
                        $user['star'] = '0';
                    }else if($prifitSum->num >= 15 && $prifitSum->num <= 19){  //15-19单
                        $user['grade'] = '1';
                        $user['star'] = '1';
                    }else if($prifitSum->num >= 20 && $prifitSum->num <= 24){  //20-24单
                        $user['grade'] = '2';
                        $user['star'] = '1';
                    }else if($prifitSum->num >= 25 && $prifitSum->num <= 30){  //25-30单
                        $user['grade'] = '3';
                        $user['star'] = '1';
                    }

                    $user['liansheng'] = 0;
                    $user['lianbai'] = 0;
                   
                    $update_member = DB::table('waihui_member')->where('id',$session_data['id'])->update($user);
                    if(!$update_member){
                       // echo 'bbbbbbbbbbbbbbbbbbb';
                        return json_encode(array('status'=>0));   //数据错误
                    }                                    
                }else if($userInfo && $userInfo->alltraid > $dingjinum){  //如果用户已定级
                    $aa = $userInfo->star + 1;
                    $bb=$userInfo->star - 1;
                    if($userInfo->grade == 0){  //如果用户段位是策略能手，即 0-14单正确
                        if($userInfo->liansheng >= $liansheng){  //如果用户连胜5单
                            $user['grade'] = '1';
                            $user['star'] = '1';
                            $user['liansheng'] = 0;
                        }
//                        else if($userInfo->lianbai >= $lianbai){  //此时不做操作
//                            
//                        }
                    }else if($userInfo->grade == 1){  //如果用户段位是交易高手，即 15-19单正确
                        if($userInfo->liansheng >= $liansheng){  //如果用户连胜5单
                            if($userInfo->star < 3){
                                //$aa = $userInfo->star + 1;
                                $user['star'] = "$aa";
                            }else if($userInfo->star == 3){
                                $user['grade'] = '2';
                                $user['star'] = '1';
                            }
                            $user['liansheng'] = 0;
                        }else if($userInfo->lianbai >= $lianbai){
                            if($userInfo->star > 1){
                                //$bb=$userInfo->star - 1;
                                $user['star'] = "$bb";
                            }else{
                                $user['grade'] = '0';
                                $user['star'] = '0';
                            }
                            $user['lianbai'] = 0;
                        }
                     
                    }else if($userInfo->grade == 2){  //如果用户段位是分析专家，即 20-24单正确
                        if($userInfo->liansheng >= $liansheng){  //如果用户连胜5单
                            if($userInfo->star < 3){
                                //$aa = $userInfo->star + 1;
                                $user['star'] = "$aa";
                            }else if($userInfo->star == 3){
                                $user['grade'] = '3';
                                $user['star'] = '1';
                            }
                            $user['liansheng'] = 0;
                        }else if($userInfo->lianbai >= $lianbai){
                            if($userInfo->star > 1){
                                //$bb = $userInfo->star - 1;
                                $user['star'] = "$bb";
                            }else{
                                $user['grade'] = '1';
                                $user['star'] = '3';
                            }
                            $user['lianbai'] = 0;
                        }
                    }else if($userInfo->grade == 3){  //如果用户段位是操盘大师，即 25-30单正确
                        if($userInfo->liansheng >= $liansheng){  //如果用户连胜5单
                            if($userInfo->star < 3){
                                //$aa = $userInfo->star + 1;
                                $user['star'] = "$aa";
                            }else if($userInfo->star == 3){
                                $user['grade'] = '4';
                                $user['star'] = '1';
                            }
                            $user['liansheng'] = 0;
                        }else if($userInfo->lianbai >= $lianbai){
                            if($userInfo->star > 1){
                                //$bb = $userInfo->star - 1;
                                $user['star'] = "$bb";
                            }else{
                                $user['grade'] = '2';
                                $user['star'] = '3';
                            }
                            $user['lianbai'] = 0;
                        }
                    }else if($userInfo->grade == 4){  //如果用户段位是金融大师
                        if($userInfo->liansheng >= $liansheng){  //如果用户连胜5单
                            if($userInfo->star < 3){
                                //$aa = $userInfo->star + 1;
                                $user['star'] = "$aa";
                                $user['liansheng'] = 0;
                            }
//                                    else if($userInfo->star == 38099){
//                                        $user['grade'] = 4;
//                                        $user['star'] = 0;
//                                    }
                        }else if($userInfo->lianbai >= $lianbai){
                            if($userInfo->star > 1){
                                //$bb = $userInfo->star - 1;
                                $user['star'] = "$bb";
                            }else{
                                $user['grade'] = '3';
                                $user['star'] = '3';
                            }
                            $user['lianbai'] = 0;
                        }
                    }
                    if($user != ''){  //更新用户的等级
                       $updateResult = DB::table('waihui_member')->where('id',$session_data['id'])->update($user);
                        if(!$updateResult){
                            return json_encode(array('status'=>0));   //数据错误
                        }
                    }
                }
                
                if($data){
                    $update_res = DB::table('waihui_order')->where('id',$list->id)->update($data);
                    if($data['money'] != 0){
                        $updateJifen = DB::table('waihui_member')->where('id',$session_data['id'])->increment('jifen', $data['money']);
                    }
                    if($update_res){
                        return json_encode(array('status'=>1));   //平仓成功
                    }else{
                        return json_encode(array('status'=>0));   //平仓失败
                    }
                }
            }else{
                return json_encode(array('status'=>0));  //平仓失败，数据库中并无此记录
            }
        }else{
            return json_encode(array('status'=>0));  //平仓失败，用户并未登录
        }    

    }
    
    
    public function allclose(Request $request){   //批量平仓
        $session_data = $request->session()->get('eai');
        if($session_data){
            $tradeid  = trim($request->tradeid);  //没加验证
            
            $infodata="{   
                        head: {
                          account: '$session_data[tel]',
                          tradecode: 8803,
                          allsend:0
                        },
                        body: {
                          fromsource: 'netpage',
                          trader_orderid : '$tradeid',
                        }
                    }&
                    ";
                $info_zheng = HandanController::sendBaoWen($infodata,'close'); //正向
//                Storage::append('close.txt', date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info_zheng['ret_code']);
                //dd($info_zheng);
                if($info_zheng['ret_code'] == '0000'){
                    $r = 1;
                }else{
                    $r = 0;
                }
                return json_encode($r);
        }    
    }
    
    
    //定时任务处理
    public function orderhandle(){
        header("Content-Type: text/html; charset=utf8");
        $money = getenv('reward');
        $list = DB::table('waihui_order')->where([['isstop','=',1],['ispersonal','=',0]])->get()->toArray();
        if($list){
            //$url = "http://db2015.wstock.cn/wsDB_API2/stock.php?symbol=FXXAUUSD,FXUSDCHF,FXGBPUSD,FXUSDJPY,FXUSDCAD ,FXEURUSD,FXAUDUSD,FXEURGBP,FXEURJPY,FXEURAUD,FXEURCHF,FXEURCAD,FXGBPCHF,FXGBPJPY ,FXCADJPY,FXAUDCAD,FXCHFJPY,FXAUDJPY&query=Date,Symbol,SP1,BP1&u=test&p=8e6a&r_type=2&num=20";
            $url = "http://db2015.wstock.cn/wsDB_API2/stock.php?market=FX&u=test&p=8e6a&r_type=2&num=200";
            $contents = file_get_contents("compress.zlib://".$url);
            dd($contents);
            $res=json_decode($contents);
            
            foreach ($res as $rkey=>$rval){
                 //$rval=json_decode($rval);
                foreach ($list as $lkey=>$lval){
                    $istrue = 0;
                    $data   = [];
                    if(substr($rval->Symbol,2) == $lval->typename){
                        if($lval->buy_status == 0){ //0:买空
                            if($lval->target_loss_point <= $rval->BP1){
                                $data['end_point']    = $rval->BP1;
                                $data['trade_status'] = 0;//亏钱
                                $data['money']        = 0;
                                $istrue    = 1;
                            }elseif($lval->target_profit_point >= $rval->BP1){
                                $data['end_point']    = $rval->BP1;
                                $data['trade_status'] = 1;//赢钱
                                $data['money']        = $money;
                                $istrue    = 1;
                                DB::table('waihui_member')->increment('profile', $money, ['tel' => $lval->tel]);
                            }else{
                                $istrue    = 0;
                            }
                        }else{ //1:买多
                            if($lval->target_loss_point >= $rval->SP1){
                                $data['end_point']    = $rval->SP1;
                                $data['trade_status'] = 0;//亏钱
                                $data['money']        = 0;
                                $istrue    = 1;
                            }elseif($lval->target_profit_point <= $rval->SP1){
                                $data['end_point']    = $rval->SP1;
                                $data['trade_status'] = 1;//赢钱
                                $data['money']        = $money;
                                $istrue    = 1;
                                DB::table('waihui_member')->increment('profile', $money, ['tel' => $lval->tel]);
                            }else{
                                $istrue    = 0;
                            }
                        }
                        if($istrue){
                            $data['end_time']  = strtotime('now');
                            $data['isstop']    = 0;
                            $data['stop_status'] = 1;
                            DB::table('waihui_order')->where(array('id'=>$lval->id))->update($data);
                        }
                    }
                }
            }
        }
    }
    
    public function updateorder(Request $request){  //修改订单
        $sessiondata   = $request->session()->get('eai');
        $tel  = $sessiondata['tel'];
        if(!$tel){
            $status = 0; 
            return json_encode($status);
        }
        $tradeid = htmlspecialchars(trim($request->tradeid)); //订单号
        $profitPoint = intval(trim($request->profitPoint)); //用户输入的止盈点数
        $lossPoint = intval(trim($request->lossPoint)); //用户输入的止损点数
        $lastLossPoint = htmlspecialchars(trim($request->lastLossPoint));  //修改完的止损点位
        $lastProfitPoint = htmlspecialchars(trim($request->lastProfitPoint)); //修改完的止盈点位
        
        if($lossPoint > 0){
            if($lossPoint<=10 || $lossPoint >=100){
                $return['status']=0;  //修改失败
                return json_encode($return);
            }
        }
        
        if($profitPoint > 0){
            if($profitPoint<=10 || $profitPoint >=500){
                $return['status']=0;  //修改失败
                return json_encode($return);
            }
        }
        
        $id = DB::table('waihui_order')->select('tel','isstop','typename','begin_point','buy_status','target_loss_point','target_profit_point','loss_point','profit_point')->where('tradeid',$tradeid)->first();
        if(!$id){ //此订单不存在
            $status = 0;
            return json_encode($status);
        }else if($id->tel != $tel){  //如果当前订单不属于当前登录用户
            $status = 0;
            return json_encode($status);
        }
        
        $symbol          = $id->typename;
        $openprice       = $id->begin_point;
        $ordertype       = $id->buy_status;
        $lastLossPoint   = $lastLossPoint ? $lastLossPoint : $id->target_loss_point;
        $lastProfitPoint = $lastProfitPoint ? $lastProfitPoint : $id->target_profit_point;
        $lossPoint   = $lossPoint ? $lossPoint : $id->loss_point;
        $profitPoint = $profitPoint ? $profitPoint : $id->profit_point;
//        $fanbenginpoint  = $id->other_begin_point;
        if($id->isstop == 1){ 
            //判断有没有人订阅该分析师
            $direction= DB::table('waihui_follow')->where([['analyst_id','=',$sessiondata['id']],['status','=','1']])->first();
            if($direction){
                $infodata="{   
                    head: {
                      account: '$tel',
                      tradecode: 8802
                    },
                    body: {
                      fromsource: 'netpage',
                      trader_orderid : '$tradeid',
                      symbol:'$symbol',
                      openprice:'$openprice',
                      stoploss:'$lastLossPoint',
                      takeprofit:'$lastProfitPoint',
                      ordertype:'$ordertype',
                      direct:0
                    }
                }&
                ";
                
                $info_zheng = HandanController::sendBaoWen($infodata,'update'); //正向
//                Storage::append('updateorder.txt', date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info_zheng['ret_code']);
                if($info_zheng['ret_code'] == '0000'){
                    $info = DB::table("waihui_order")->where('tradeid',$tradeid)->update(['target_profit_point' => $lastProfitPoint,'target_loss_point'=>$lastLossPoint,'loss_point'=>$lossPoint,'profit_point'=>$profitPoint]);
                    if($info){
                        $status = 1;

                    }else{
                        $status = 0;
                    }
                }else{
                    $status = 0;
                }
            }else{  //如果没有人订阅该分析师，那么就不需要发送报文
                $info = DB::table("waihui_order")->where('tradeid',$tradeid)->update(['target_profit_point' => $lastProfitPoint,'target_loss_point'=>$lastLossPoint,'loss_point'=>$lossPoint,'profit_point'=>$profitPoint]);
                if($info){
                    $status = 1;

                }else{
                    $status = 0;
                }
            }
            
        }else{
            $status = 0;
        }
        
        return json_encode($status);
    }
    
    public function goDelOrder(Request $request){  //提交申请删除前20单
        if(intval($request->uid) != 0){
            $id = intval($request->uid);
            if($id == $request->session()->get('eai')['id']){
                $user = DB::table('waihui_member')->select('id')->where('id','=',$id)->first();
                if($user){
                    $hasApply = DB::table('waihui_deltop20')->select('id')->where('userid','=',$id)->first();
                    if(!$hasApply){
                        $id = DB::table('waihui_deltop20')->insertGetId(['userid'=>$id,'tel'=>$request->session()->get('eai')['tel']]);
                        if($id){
                            return 1;
                        }else{
                            return 0;
                        }
                    }else{
                       return 2; 
                    }
                    
                }else{
                    return 0;
                } 
            }else{
                 return 0;
            }
            
        }
    }
    
    public function deletetop20(){  //删除前20单,先删除order表的20单，然后再更新member的alltrade-20，最后更新deltop20的type字段
        $all = DB::table('waihui_deltop20')
               ->select('tel') 
               ->where('type','0')
               ->get()->toArray();  
        //dd($all);
        foreach($all as $val){
            $deleteOrder =  DB::table('waihui_order')  //先删除order表的20单
                    ->where([['tel','=',$val->tel],['isstop','=',0]])
                    ->orderBy('end_time','asc')    
                    ->limit(20)
                    ->delete(); 
            //$deleteOrder=20;
            if($deleteOrder){ 
                $alltraid = DB::table('waihui_member')
                            ->where([['tel','=',$val->tel],['alltraid','>',20]]) 
                            ->value('alltraid'); 
                //dd($alltraid);
                if($alltraid != 0){
                    $updateAllTraid = $alltraid-20;
                }else{
                    return $val->tel.'删除失败！';
                }
               
                if($updateAllTraid < 30){  //如果删除20后，总单量小于30单，那么取消用户的定级
                    $user = array('alltraid'=>$updateAllTraid,'star'=>'0','grade'=>'-1','lianbai'=>0,'liansheng'=>0);
                }else{ //如果删除20后，总单量大于等于30单，那么重新给用户定级
                    $user['alltraid'] = $updateAllTraid;
                    $qian30dan = DB::table('waihui_order')   //先查询前30单
                                 ->select('trade_status')
                                 ->where([['tel','=',$val->tel],['ispersonal','=','0'],['isstop','=','0']])
                                 ->orderBy('end_time','asc')
                                 ->limit(30)
                                 ->get()->toArray();
                    //dd($qian30dan);  
                    $i = 0;
                    foreach($qian30dan as $v){
                        if($v->trade_status == 1){
                            $i++;
                        }
                    }    
                    
                    
                    if($i <= 14){  //0-14单
                        $user['grade'] = '0';
                        $user['star'] = '0';
                    }else if($i >= 15 && $i <= 19){  //15-19单
                        $user['grade'] = '1';
                        $user['star'] = '1';
                    }else if($i >= 20 && $i <= 24){  //20-24单
                        $user['grade'] = '2';
                        $user['star'] = '1';
                    }else if($i >= 25 && $i <= 30){  //25-30单
                        $user['grade'] = '3';
                        $user['star'] = '1';
                    }

                    $user['liansheng'] = 0;
                    $user['lianbai'] = 0;
                }
                //dd($user);
                $updateMemberTrade = DB::table('waihui_member')
                                    ->where([['tel','=',$val->tel]])   
                                    ->update($user);
                if($updateMemberTrade){
                    $updateDelType = DB::table('waihui_deltop20')
                                     ->where('tel',$val->tel)
                                     ->update(['type'=>1]);
                    if($updateDelType){
                        echo '删除成功！';
                    }else{
                        echo $val->tel.'删除失败！';
                    }
                }
            }
        } 
        
    }
    
     
}
